const {src,dest,series,watch} = require("gulp");

const sass = require("gulp-sass");
	  sass.compiler = require("node-sass");

const autoprefixer = require('gulp-autoprefixer');

//引入静态服务器
const browserSync = require("browser-sync").create();

//引入压缩js代码
const uglify = require("gulp-uglify");
const pipeline = require("readable-stream").pipeline;

//引入压缩图片
const tinypng = require("gulp-tinypng-compress");

const devBaseUrl = "./src";

//开发环境的任务
//1.配置sass编译
//2.配置自动添加前缀-gulp-aotuprefixer

//引入静态服务器
function browsersync(cb){
	cb();
	browserSync.init({
		server:{
			baseDir:devBaseUrl
		},
		port:8888,
		files:[devBaseUrl+"**/*.html",devBaseUrl+"/**/*.css",devBaseUrl+"/js/*.js"]
	})
	watch(devBaseUrl+"/scss/**/*.scss",sass2css)
}

function sass2css(cb){
	cb();
	return src(devBaseUrl+"/scss/**/*.scss")
		   .pipe(sass().on("error",sass.logError))
		   //自动添加前缀
		   .pipe(autoprefixer({
		   		cascade:false
		   }))
		   .pipe(dest(devBaseUrl+"/css"))
}

//配置实时监听sass任务
function watchsass(cb){
	cb();
	watch(devBaseUrl+"/scss/**/*.scss",sass2css)
}

//生产环境
//复制html
function copyhtml(cb){
	cb();
	src(devBaseUrl+"/*.html")
	.pipe(dest("dist/"))
}
//压缩css
function sass2css_pro(cb){
	cb();
	return src(devBaseUrl+"/scss/**/*.scss")
		   .pipe(sass({outputStyle:"compressed"}).on("error",sass.logError))
		   //自动添加前缀
		   .pipe(autoprefixer({
		   		cascade:false
		   }))
		   .pipe(dest("dist/css"))
}
//压缩js
function uglifyjs(cb){
	cb();
	return pipeline(
		src(devBaseUrl+"/js/*.js"),
		uglify(),
		dest("dist/js")
	)
}
//压缩图片
function uglifyimg(cb){
	cb();
	src(devBaseUrl+"/img/**/*.{png,jpg,jpeg}")
	.pipe(tinypng({
		key:"y4yWdMW4TZxmmWZnksSV_rd-Nl2AYSQw",
		log:true
	}))
	.pipe(dest("dist/img"))
}

//定义生产任务

exports.sass2css = sass2css;
exports.watchsass = watchsass;
exports.browsersync = browsersync;
exports.copyhtml = copyhtml;
exports.sass2csspro = sass2css_pro;
exports.uglifyjs = uglifyjs;
exports.uglifyimg = uglifyimg;
exports.build = series(copyhtml,sass2css_pro,uglifyjs,uglifyimg);